package com.bitdf.txing.users.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.PageUtils;
import com.bitdf.txing.common.utils.Query;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.vo.UserInfoVo;
import com.bitdf.txing.users.ao.LoginRegistUserAo;
import com.bitdf.txing.users.dao.UserDao;
import com.bitdf.txing.users.entity.UserEntity;
import com.bitdf.txing.users.service.UserService;
import com.bitdf.txing.users.vo.UserQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

    /**
     * 分页查询
     * @param queryVo
     * @return
     */
    @Override
    public PageUtils queryPage(UserQueryVo queryVo) {
        // 拼接查询条件
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(queryVo.getUserName() != null, UserEntity::getUserName, queryVo.getUserName())
                .eq(queryVo.getPhone() != null, UserEntity::getPhone, queryVo.getPhone());
        IPage<UserEntity> page = this.page(
                new Query<UserEntity>().getPage(queryVo),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public R register(LoginRegistUserAo entity) {
        // 判断是否 手机号 以及 用户名 是否存在重复的
        UserEntity one = this.getOne(new QueryWrapper<UserEntity>().eq("phone", entity.getPhone()).or().eq("user_name", entity.getUserName()));
        if (one != null){
            return R.error(TxCodeEnume.USER_ALREADY_EXIST_EXCEPTION);
        }
        // 加密密码
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        entity.setPassword(passwordEncoder.encode(entity.getPassword()));

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(entity, userEntity);
        // 设置默认角色
        userEntity.setRoleId(0L);
        // 保存
        boolean save = this.save(userEntity);
        return R.ok();
    }

    /**
     * 通过ids获取用户详细信息
     * @param list
     * @return
     */
    @Override
    public List<UserInfoVo> getByUserList(List<Long> list) {
        if(list==null || list.size()==0){
            return null;
        }
        List<UserEntity> list1 = this.list(new QueryWrapper<UserEntity>().in("id", list));
        List<UserInfoVo> list2 = list1.stream().map(item -> {
            UserInfoVo userInfoVo = new UserInfoVo();
            BeanUtils.copyProperties(item, userInfoVo);
            return userInfoVo;
        }).collect(Collectors.toList());
        return list2;
    }
}